<template>
  <div>
    <AppNavbar :fetchProductData="fetchData"/>
    <h2>{{ title }}</h2>
    <div v-html="renderDescription(content)"></div>
  </div>
</template>


<script>
  import AppNavbar from '@/components/AppNavbar.vue';
  import {computed, inject, onMounted, ref} from 'vue';
  import axios from 'axios';

  export default {
    components: {
      AppNavbar
    },
    setup() {
      const currentLocale = inject('locale'); // 假设在父组件或根实例中提供

      const i18nMessages = {
        'en': {
          title: 'Custom Content',
        },
        'zh-CN': {
          title: '定制内容',
        },
      };
      const t = (key) => {
        console.log("key:",key,currentLocale.value)
        return i18nMessages[currentLocale.value][key] || key;
      };
      const title = computed(() => t('title'));

      const content = ref(''); // 使用 ref 创建响应式变量

      const fetchData = async () => {
        try {
          const response = await axios.get(process.env.VUE_APP_DOMAIN_URL + `/text/textManager/queryByPage`, {
            params: { page: '按需定制' }
          });

          if (response.data && response.data.result) {
            const result = response.data.result;
            content.value = result && currentLocale.value === 'zh-CN' ? result.chinese : result.english;
          } else {
            console.error('No data or empty result returned.');
          }
        } catch (error) {
          console.error('Error fetching data:', error);
        }
      };

      // Define renderDescription method
      const renderDescription = (description) => {
        if (!description) {
          return ''; // 如果 description 为 undefined 或 null，则返回空字符串
        }
        // 正则表达式用于匹配图片链接
        const imgRegex = /(?:https?|ftp):\/\/[\S]+\.(?:jpg|jpeg|png|gif|bmp)(?:\?[\S]*)?/gi;

        // 将图片链接替换为 <img> 标签
        const descriptionWithImages = description.replace(imgRegex, (imgUrl) => {
          return `<img src="${imgUrl}" alt="Product Image">`;
        });

        // 返回包含图片链接替换后的HTML字符串
        return descriptionWithImages;
      };


      onMounted(() => {
        fetchData();
      });

      return { content, t,title, fetchData,renderDescription };
    }
  };
</script>

<style scoped>

</style>
